<template>
  <el-form-item :label="label" :required="required">
    <el-input
      v-model="displayValue"
      :placeholder="placeholder"
      :disabled="disabled"
      readonly
      @click="showDialog = true"
    >
      <template #append>
        <el-button :disabled="disabled" @click="showDialog = true">
          <el-icon><search /></el-icon>
        </el-button>
      </template>
    </el-input>

    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="50%"
      :before-close="handleClose"
    >
      <slot name="dialog-content"></slot>
      
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </el-form-item>
</template>

<script lang="ts">
import { defineComponent, ref, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'

export default defineComponent({
  name: 'DialogSelectControl',
  components: { Search },
  props: {
    modelValue: {
      type: [String, Number, Array],
      default: ''
    },
    label: {
      type: String,
      default: ''
    },
    required: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    dialogTitle: {
      type: String,
      default: '请选择'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    formatter: {
      type: Function,
      default: (value: any) => String(value)
    }
  },
  emits: ['update:modelValue', 'confirm'],
  setup(props, { emit }) {
    const showDialog = ref(false)
    const tempValue = ref(props.modelValue)

    const displayValue = computed(() => {
      return props.formatter(props.modelValue)
    })

    const handleClose = () => {
      showDialog.value = false
    }

    const handleConfirm = () => {
      emit('update:modelValue', tempValue.value)
      emit('confirm', tempValue.value)
      showDialog.value = false
    }

    return {
      showDialog,
      displayValue,
      handleClose,
      handleConfirm
    }
  }
})
</script>